﻿using ArtMath.Core.Helper;
using ArtMath.Flag;
using ArtMath.Resource;
using ArtMath.Setting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;

namespace ArtMath.Window
{
    public partial class DocumentRecoverWindow : Form
    {
        public DocumentRecoverWindow()
        {
            InitializeComponent();
            foreach (KeyValuePair<string, string> item in UserOptions.Instance.AutoSaveNewestPath)
            {
                string title, path;
                Document doc = getDocumentFromFile(item.Key);
                if (doc == null)
                {
                    doc = getDocumentFromFile(item.Value);
                    if (doc == null) continue;
                    title = doc.Title;
                    if (int.TryParse(item.Key, out int hash))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = item.Key;
                    }
                }
                else
                {
                    title = doc.Title;
                    path = item.Key;
                }
                listView1.Items.Add(new ListViewItem(new string[] { title, path }) { Tag = item.Value });
            }
        }
        Document getDocumentFromFile(string path)
        {
            IFormatter fmt = new BinaryFormatter();
            try
            {
                FileStream stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
                object[] objs = fmt.Deserialize(stream) as object[];
                stream.Close();
                return objs[0] as Document;
            }
            catch (Exception)
            {

            }
            return null;
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            Flags.DeleteTemporaryFiles();
            DialogResult = DialogResult.Cancel;
        }

        private void btnRecover_Click(object sender, EventArgs e)
        {
            recover(false);
            DialogResult = DialogResult.OK;
        }

        private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            btnRecover.Enabled = btnRecoverAndDelete.Enabled = listView1.CheckedItems.Count > 0;
        }

        private void listView1_SizeChanged(object sender, EventArgs e)
        {
            int width = listView1.ClientSize.Width - 30;
            listView1.Columns[0].Width = (int)(width * 0.4);
            listView1.Columns[1].Width = (int)(width * 0.6);
        }
        void recover(bool overwrite)
        {
            foreach (ListViewItem item in listView1.CheckedItems)
            {
                string tmpPath = item.Tag as string, dest;
                bool discardFile;
                if (string.IsNullOrEmpty(item.SubItems[1].Text))
                {
                    dest = tmpPath;
                    discardFile = true;
                }
                else
                {
                    try
                    {
                        if (overwrite)
                        {
                            dest = item.SubItems[1].Text;
                        }
                        else
                        {
                            string dir = Path.GetDirectoryName(item.SubItems[1].Text),
                                filename = Path.GetFileNameWithoutExtension(item.SubItems[1].Text);
                            dest = dir + "\\" + Utility.GetNextAvailableName(filename + Resources.LeftParenthesis + Resources.Translate("Recover") + Resources.RightParenthesis, (string name) => { return File.Exists(dir + "\\" + name + Flags.DocumentExtension); }) + Flags.DocumentExtension;
                        }
                        File.Copy(tmpPath, dest, overwrite);
                        discardFile = false;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                        continue;
                    }
                }
                Document doc = Program.WinDocuments.OpenDocument(dest);
                if (doc != null)
                {
                    if (discardFile)
                    {
                        if (doc.LinkedFile != null)
                        {
                            doc.LinkedFile.Close();
                            doc.LinkedFile = null;
                        }
                    }
                }
            }
            Flags.DeleteTemporaryFiles(true);
        }
        private void btnRecoverAndDelete_Click(object sender, EventArgs e)
        {
            recover(true);
            DialogResult = DialogResult.OK;
        }
    }
}
